import errorLogger from '../../utils/error-logger';
import { setErrorLogEnabled } from '../../utils/env';

Page({
  data: {
    errorLogEnabled: true,
    testResults: []
  },
  onLoad() {
    // 页面加载时，初始化错误日志状态
    this.updateLogStatus();
  },
  
  // 更新日志状态显示
  updateLogStatus() {
    const errorLogEnabled = this.data.errorLogEnabled;
    this.setData({
      errorLogEnabled
    });
  },
  
  // 切换错误日志开关
  toggleErrorLog() {
    const newStatus = !this.data.errorLogEnabled;
    setErrorLogEnabled(newStatus);
    this.setData({
      errorLogEnabled: newStatus
    });
    this.addTestResult(`错误日志收集${newStatus ? '已开启' : '已关闭'}`);
  },
  
  // 添加测试结果
  addTestResult(message) {
    const testResults = this.data.testResults;
    testResults.unshift({
      id: Date.now(),
      time: new Date().toLocaleTimeString(),
      message
    });
    
    // 最多显示20条
    if (testResults.length > 20) {
      testResults.pop();
    }
    
    this.setData({
      testResults
    });
  },
  
  // 测试JS错误
  testJsError() {
    try {
      const nullObject = null;
      nullObject.nonExistentMethod(); // 会抛出TypeError
    } catch (error) {
      this.addTestResult(`捕获到JS错误: ${error.message}`);
      errorLogger.log({
        type: 'js',
        error,
        message: '测试JS错误',
        source: 'error-test'
      });
    }
  },
  
  // 测试Promise拒绝错误
  testPromiseError() {
    const failedPromise = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('测试Promise被拒绝'));
      }, 100);
    });
    
    failedPromise.catch(error => {
      this.addTestResult(`捕获到Promise错误: ${error.message}`);
      errorLogger.log({
        type: 'promise',
        error,
        message: '测试Promise错误',
        source: 'error-test'
      });
    });
  },
  
  // 测试网络错误
  testNetworkError() {
    wx.request({
      url: 'https://non-existent-domain-12345.com/api',
      fail: error => {
        this.addTestResult(`捕获到网络错误: ${error.errMsg}`);
        errorLogger.log({
          type: 'network',
          error,
          message: '测试网络请求错误',
          source: 'error-test'
        });
      }
    });
  },
  
  // 测试自定义错误
  testCustomError() {
    const customError = {
      name: 'CustomError',
      message: '这是一个自定义错误对象',
      code: 'CUSTOM_ERR_001',
      additionalInfo: '包含额外信息的自定义错误'
    };
    
    this.addTestResult(`记录自定义错误: ${customError.message}`);
    errorLogger.log({
      type: 'custom',
      error: customError,
      message: '测试自定义错误',
      source: 'error-test',
      extra: {
        customField: '自定义字段',
        timestamp: Date.now()
      }
    });
  },
  
  // 手动刷新错误日志
  flushLogs() {
    errorLogger.flush(true);
    this.addTestResult('手动触发日志上传');
  },
  
  // 清除测试结果
  clearTestResults() {
    this.setData({
      testResults: []
    });
  }
}); 